import React, { useState, useEffect, useRef, useCallback } from 'react';
import {
  Card,
  Table,
  Button,
  Input,
  Space,
  Modal,
  Form,
  Select,
  Tag,
  Popconfirm,
  Toast,
  Typography,
  Row,
  Col,
} from '@douyinfe/semi-ui';
import {
  IconPlus,
  IconSearch,
  IconEdit,
  IconDelete,
  IconRefresh,
} from '@douyinfe/semi-icons';
import { permissionApi, SysPermission } from '../../api/permission';
import { PageQuery } from '../../api/request';

const { Title } = Typography;
const { Column } = Table;

const PermissionManagement: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [permissions, setPermissions] = useState<SysPermission[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [keyword, setKeyword] = useState('');
  const [modalVisible, setModalVisible] = useState(false);
  const [editingPermission, setEditingPermission] = useState<SysPermission | null>(null);
  const formRef = useRef<any>();

  useEffect(() => {
    loadPermissions();
  }, [currentPage, pageSize, keyword]);

  const loadPermissions = async () => {
    setLoading(true);
    try {
      const params: PageQuery = {
        current: currentPage,
        size: pageSize,
        keyword,
      };
      const response = await permissionApi.pagePermissions(params);
      setPermissions(response.records);
      setTotal(response.total);
    } catch (error) {
      console.error('加载权限列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = () => {
    setCurrentPage(1);
    loadPermissions();
  };

  const handleReset = () => {
    setKeyword('');
    setCurrentPage(1);
    setTimeout(() => loadPermissions(), 0);
  };

  const handleAdd = useCallback(() => {
    setEditingPermission(null);
    if (formRef.current) {
      formRef.current.reset();
    }
    setModalVisible(true);
  }, []);

  const handleEdit = useCallback((permission: SysPermission) => {
    setEditingPermission(permission);
    if (formRef.current) {
      formRef.current.setValues(permission);
    }
    setModalVisible(true);
  }, []);

  const handleDelete = async (id: number) => {
    try {
      await permissionApi.deletePermission(id);
      Toast.success('删除成功');
      loadPermissions();
    } catch (error) {
      console.error('删除失败:', error);
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      if (editingPermission) {
        await permissionApi.updatePermission({ ...values, id: editingPermission.id });
        Toast.success('更新成功');
      } else {
        await permissionApi.createPermission(values);
        Toast.success('创建成功');
      }
      setModalVisible(false);
      loadPermissions();
    } catch (error) {
      console.error('操作失败:', error);
    }
  };

  const getStatusTag = (status: number) => {
    return status === 1 ? (
      <Tag color="green">启用</Tag>
    ) : (
      <Tag color="red">禁用</Tag>
    );
  };

  const getPermissionTypeTag = (type: number) => {
    switch (type) {
      case 1:
        return <Tag color="blue">菜单</Tag>;
      case 2:
        return <Tag color="green">按钮</Tag>;
      case 3:
        return <Tag color="orange">API</Tag>;
      default:
        return <Tag color="grey">未知</Tag>;
    }
  };

  const getPermissionTypeText = (type: number) => {
    switch (type) {
      case 1:
        return '菜单';
      case 2:
        return '按钮';
      case 3:
        return 'API';
      default:
        return '未知';
    }
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
    },
    {
      title: '权限名称',
      dataIndex: 'permissionName',
      width: 150,
    },
    {
      title: '权限编码',
      dataIndex: 'permissionCode',
      width: 200,
      render: (code: string) => (
        <code className="bg-gray-100 px-2 py-1 rounded text-sm">
          {code}
        </code>
      ),
    },
    {
      title: '权限类型',
      dataIndex: 'permissionType',
      width: 100,
      render: (type: number) => getPermissionTypeTag(type),
    },
    {
      title: '描述',
      dataIndex: 'description',
      width: 200,
      render: (text: string) => (
        <div className="truncate" title={text}>
          {text}
        </div>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      render: (status: number) => getStatusTag(status),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 160,
      render: (time: string) => time?.substring(0, 19),
    },
    {
      title: '操作',
      width: 150,
      render: (record: SysPermission) => (
        <Space>
          <Button
            theme="borderless"
            type="primary"
            size="small"
            icon={<IconEdit />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定删除这个权限吗？"
            onConfirm={() => handleDelete(record.id!)}
          >
            <Button
              theme="borderless"
              type="danger"
              size="small"
              icon={<IconDelete />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className="space-y-4">
      <Card>
        <div className="flex justify-between items-center mb-4">
          <Title heading={4}>权限管理</Title>
          <Button
            type="primary"
            icon={<IconPlus />}
            onClick={handleAdd}
          >
            新增权限
          </Button>
        </div>

        <Row gutter={16} className="mb-4">
          <Col span={8}>
            <Input
              placeholder="搜索权限名称、权限编码、描述"
              value={keyword}
              onChange={setKeyword}
              onEnterPress={handleSearch}
            />
          </Col>
          <Col>
            <Space>
              <Button
                type="primary"
                icon={<IconSearch />}
                onClick={handleSearch}
              >
                搜索
              </Button>
              <Button
                icon={<IconRefresh />}
                onClick={handleReset}
              >
                重置
              </Button>
            </Space>
          </Col>
        </Row>

        <Table
          columns={columns}
          dataSource={permissions}
          loading={loading}
          pagination={{
            current: currentPage,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            onChange: (page, size) => {
              setCurrentPage(page);
              setPageSize(size!);
            },
          }}
          rowKey="id"
        />
      </Card>

      {/* 权限表单弹窗 */}
      <Modal
        title={editingPermission ? '编辑权限' : '新增权限'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          getFormApi={(formApi) => (formRef.current = formApi)}
          onSubmit={handleSubmit}
          labelPosition="left"
          labelWidth={100}
          labelAlign="left"
          autoScrollToError
          showValidateIcon
          onSubmitFail={(errors) => {
            console.error('表单验证失败:', errors);
            Toast.error('请检查表单输入');
          }}
        >
          <Form.Input
            field="permissionName"
            label="权限名称"
            placeholder="请输入权限名称"
            rules={[{ required: true, message: '请输入权限名称' }]}
          />
          
          <Form.Input
            field="permissionCode"
            label="权限编码"
            placeholder="请输入权限编码，如：system:user:add"
            rules={[
              { required: true, message: '请输入权限编码' },
              { pattern: /^[a-z:]+$/, message: '权限编码只能包含小写字母和冒号' },
            ]}
            disabled={!!editingPermission}
          />
          
          <Form.Select
            field="permissionType"
            label="权限类型"
            placeholder="请选择权限类型"
            rules={[{ required: true, message: '请选择权限类型' }]}
          >
            <Select.Option value={1}>菜单</Select.Option>
            <Select.Option value={2}>按钮</Select.Option>
            <Select.Option value={3}>API</Select.Option>
          </Form.Select>
          
          <Form.TextArea
            field="description"
            label="权限描述"
            placeholder="请输入权限描述"
            maxCount={200}
            rules={[{ required: true, message: '请输入权限描述' }]}
          />
          
          <Form.Select
            field="status"
            label="状态"
            placeholder="请选择状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select.Option value={1}>启用</Select.Option>
            <Select.Option value={0}>禁用</Select.Option>
          </Form.Select>
          
          <div className="flex justify-end space-x-2 mt-6">
            <Button onClick={() => setModalVisible(false)}>
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </div>
        </Form>
      </Modal>
    </div>
  );
};

export default PermissionManagement;